package spt.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XMLUtils {
	private static final Logger log = Logger.getLogger(XMLUtils.class.getName());
	
	public static Document newDocument(){
		Document document = null;
		try {
			document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		} catch (ParserConfigurationException e) {
			log.severe(e.getMessage());
		}
		
		return document;
	}
	
	public static Document parseDocument(String xml){
		try {
			return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stringToInputStream(xml));
		} catch (UnsupportedEncodingException e) {
			log.severe(e.getMessage());
		} catch (SAXException e) {
			log.severe(e.getMessage());
		} catch (IOException e) {
			log.severe(e.getMessage());
		} catch (ParserConfigurationException e) {
			log.severe(e.getMessage());
		}
		
		return null;
	}
	
	public static String transformToString(Document doc){
		return transformToString(doc, false);
	}
	
	public static String transformToString(Document doc, boolean omitDeclaration){
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer t;
		Writer outWriter = null;
		try {
			t = tf.newTransformer();
			t.setOutputProperty(OutputKeys.INDENT, "yes");
			if(omitDeclaration)
				t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

			outWriter = new StringWriter();
			StreamResult result = new StreamResult(outWriter);

			t.transform(new DOMSource(doc), result);
		} catch (TransformerConfigurationException e) {
			log.severe(e.getMessage());
		} catch (TransformerException e) {
			log.severe(e.getMessage());
		}
		
		return (outWriter != null) ? outWriter.toString() : null;
	}
	
	private static InputStream stringToInputStream(String r) throws UnsupportedEncodingException {
		return new ByteArrayInputStream(r.getBytes("UTF-8"));
	}
}
